<template>
  <view class="songDetailContainer">
    <view class="bg" :style="{ backgroundImage: `url(${song.imageUrlUrl ? song.imageUrlUrl : '../../static/logo.png'})` }">
    </view>
    <view class="content">
      <view class="title">{{ song.title }}</view>
      <view class="discContainer discAnimation " :class="{ paused: !isPlay, running: isPlay }" v-if="current === 0">
        <view class="disc"></view>
        <view class="circle">
          <image class="musicImg" :src="song.imageUrlUrl ? song.imageUrlUrl : '../../static/logo.png'"></image>
        </view>
      </view>
      <view v-if="current === 1">
        <tm-scrolly class="h-full">
          <!-- <view class="prompt" v-html="song.lyric" style="white-space: pre-line"> </view> -->
          <view v-if="!commentList || commentList.length === 0"
            class="flex content-center justify-center items-center h-full">暂无评论</view>
          <view class="mb-1" v-for="item in commentList" :key="item.commentId">
            <tm-comment class="p-0" :margin="[0, 0]" :padding="[6, 6]">
              <template v-slot:author>
                <view class="flex ">
                  <image :src="item.user.avatarUrlUrl" class="rounded-full w-5 h-5 mr-2"></image>
                  <tm-text>{{ item.user.nickname }}</tm-text>
                </view>
              </template>
              <template v-slot:content>
                <tm-text>{{ item.content }}</tm-text>
              </template>
              <template v-slot:time>
                <tm-text class="color-black" >{{item.createTime}}</tm-text>
              </template>
              <!-- <template v-slot:time>
              <tm-text></tm-text>
            </template> -->
            </tm-comment>
          </view>
        </tm-scrolly>
        <view class="absolute bottom-50 left-0 right-0  flex content-center justify-center items-center p-2">
          <tm-input class="w-140 " placeholder="请输入评论内容" v-model="content" :height="40"></tm-input>
          <tm-button class="ml-10 w-20 " :height="40" @click="publish()" size="small" round>发表</tm-button>
        </view>
      </view>

      <tm-drawer ref="calendarView" placement="right" v-model:show="showDrawer">
        <view class="flex justify-between items-center p-2" v-for="item,index in audioList" @click="changeAudio(index)">
          <!-- <tm-text :label="item"></tm-text> -->
          <tm-text _class="text-overflow-1" class="w-30" :label="item.title"></tm-text>
          <tm-text>{{moment(item.duration*1000).format('mm:ss')}}</tm-text>
          <tm-text :label="song.musicId === item.musicId ? '正在播放' : ''"></tm-text>
        </view>
        <!-- inContent -->
        <!-- <tm-picker :height="500" inContent v-model:show="showWin2" :columns="citydate"></tm-picker> -->
      </tm-drawer>



      <tm-tabs class="u-tabs-con" :list="list1" @change="handleChange" :gutter="20" tabPos="bottom" transprent
        :defaultName="0" activeFontColor="white"></tm-tabs>
      <!-- <view class="share">
              <u-icon name="share" color="#fff" size="40" @click="shareClick"></u-icon>
              <text> 分享 </text>
          </view> -->
      <!-- 进度条控制区域 -->
      <view class="progressControl">
        <text>{{ currentTimeText }}</text>
        <slider style="width: 560rpx" @change="handleSliderChange" :value="sliderIndex" :max="maxSliderIndex"
          activeColor="#ea588e" backgroundColor="#b9c2c5" block-color="#fff" block-size="12" />
        <text>{{ totalTimeText }}</text>
      </view>

      <!-- 底部控制播放区域 -->
      <view class="musicControl">
        <tm-icon :font-size="60" name="tmicon-heart-fill"  :color="isLiked?'red':'#fff'" size="60" @click="clickLike(song.musicId)"></tm-icon>
        <tm-icon :font-size="60" name="tmicon-angle-double-left" @click="handlePrev" color="#fff" size="60"
          id="pre"></tm-icon>
        <tm-icon :font-size="60" name="tmicon-pausecircle-fill" @click="onPauseAudio" v-if="isPlay" color="#fff"
          size="80"></tm-icon>
        <tm-icon :font-size="60" name="tmicon-playcircle-fill" @click="onPlayAudio" v-if="!isPlay" color="#fff"
          size="80"></tm-icon>
        <tm-icon :font-size="60" name="tmicon-angle-double-right" @click="handleNext" color="#fff" size="60"
          id="next"></tm-icon>
        <tm-icon :font-size="60" name="tmicon-all" @click="showDrawer = true" color="#fff" size="60"></tm-icon>
      </view>
    </view>
  </view>
  <!-- <u-action-sheet class="action-sheet" :list="data.list" v-model="show" @click="sheetClick"
    cancel-text="关闭"></u-action-sheet> -->
  <!-- #ifdef H5 -->
</template>

<script lang="ts" setup>
import { ref, reactive, onUnmounted, toRaw, computed, watch } from 'vue';
import moment from 'moment'
import { onLoad,onShow } from '@dcloudio/uni-app'
// import { download } from '@/utils/download'
import { drawingRecord } from '@/api/music'
// import result from './result.json'
import { getCommentByMusic as getComment, publishComment, getCommentByMusic } from '../../api/music/index';
import { likeMusic, getUserBehaviorByMusic } from '../../api/index/index';


let id = ref(0) // 歌曲详情对象
const song = ref({}) // 歌曲详情对象
const isPlay = ref(false) // 音乐是否播放
const currentTime2 = ref(0) // 实时时间
const audioList = ref([]) // 音乐列表
let index = -1
const show = ref(false)
const innerAudioContext = uni.createInnerAudioContext()
const startId = ref(0)
const endId = ref(0)
const sliderIndex = ref(0) //滑块当前值
const maxSliderIndex = ref(100) //滑块最大值
const currentTimeText = ref('00:00') //视频已播放长度文字
const totalTimeText = ref('00:00') //视频总长度文字
const currentSong = ref({})
const showDrawer = ref(false)

const content = ref('')

const isLiked = ref(false)

const publish = () => {
  let comment = {
    content: content.value,
    musicId: song.value.musicId
  }
  publishComment(comment).then(res => {
    console.log(res);
    if (res.data.code === 200) {
      getCommentByMusic(song.value.musicId)
    }
    
  })
}

const getIsLike = (musicId) => {
  getUserBehaviorByMusic(musicId).then(res => {
    isLiked.value = res.data.data.isLiked
  })
}

const clickLike = (musicId) => {
  likeMusic(musicId).then(res => {
    if (res.data.code === 200) {
      getIsLike(musicId)
    }
  })
}

onShow(() => {
  currentSong.value = uni.getStorageSync('currentSong')
  // id.value = options.id
  // startId.value = options.startId
  // endId.value = options.endId
  getAudioList()
  getCommentByMusic(currentSong.value.musicId)

})

const changeAudio = (index) => {
  
  song.value = audioList.value[index]
  innerAudioContext.stop()
  sliderIndex.value = 0
  currentTimeText.value = '00:00'
  currentTime2.value = 0 
  onPlayAudio()
  getCommentByMusic(song.value.musicId)
}

const commentList = ref([])

const playList = ref([])

const getCommentByMusic = (musicId) => {
  getComment(musicId).then(res => {
    console.log(res);
    commentList.value = res.data.data
  })
}

const getMusicList = () => {
  let userinfo = uni.getStorageInfoSync("userinfo")
  if (userinfo) {
    console.log(userinfo);

  }
}
const getAudioList = () => {
  // const { lists } = await drawingRecord({
  //     status: 3,
  //     startId: startId.value,
  //     endId: endId.value,
  //     pageNo: 1,
  //     pageSize: 100
  // })
  // audioList.value = lists
  if(uni.getStorageSync('songs')){
    audioList.value = uni.getStorageSync('songs')
    console.log(audioList.value);
    
    
  }else{
    audioList.value = []
  }


  if (song.value.musicId && song.value.musicId === currentSong.value.musicId) {
    return 
  }
  

  // audioList.value = result.data.lists
  for (let i = 0; i < audioList.value.length; i++) {
    if (audioList.value[i].musicId === currentSong.value.musicId) {
      index = i
      console.info('index', i)
    }
  }
  if (index !== -1) {

    song.value = audioList.value[index]
    innerAudioContext.autoplay = true
    innerAudioContext.src = song.value.audioUrlUrl
    innerAudioContext.play()
    isPlay.value = true
  } else {
    if (currentSong.value) {
      console.log(currentSong.value);
      
      let music = toRaw(currentSong.value)
      audioList.value.push(music)
      uni.setStorageSync('currentSong', null)
      song.value = audioList.value[audioList.value.length - 1]
      innerAudioContext.autoplay = true
      innerAudioContext.src = song.value.audioUrlUrl
      innerAudioContext.play()
      isPlay.value = true
    } else {
      song.value = {
        title: '',
        imageUrlUrl: '',
        duration: 0,
        audioUrlUrl: ''
      }
    }

  }
}

innerAudioContext.onEnded(() => {
  isPlay.value = false
  currentTimeText.value = '00:00'
  sliderIndex.value = 0
  handleNext()
})
innerAudioContext.onTimeUpdate(() => {
  currentTimeText.value = moment(innerAudioContext.currentTime * 1000).format('mm:ss')
  sliderIndex.value = innerAudioContext.currentTime
})
innerAudioContext.onCanplay(function () {
  totalTimeText.value = moment(innerAudioContext.duration * 1000).format('mm:ss')
  maxSliderIndex.value = innerAudioContext.duration
})

innerAudioContext.onPause(() => {
  currentTime2.value = innerAudioContext.currentTime
})
innerAudioContext.onPlay(() => {
  innerAudioContext.seek(currentTime2.value)
  console.log(currentTime2.value, 'currentTime2.value')
  console.log("当前播放hook：",song.value);
  uni.setStorageSync('currentSong', song.value)
  
})

const onPauseAudio = () => {
  innerAudioContext.pause()
  isPlay.value = false
}
const onPlayAudio = () => {
  if (song.value.audioUrlUrl) {

    innerAudioContext.src = song.value.audioUrlUrl
    index = audioList.value.findIndex(item => item.musicId === song.value.musicId)
    innerAudioContext.play()
    isPlay.value = true
  } else {
    uni.showToast({
      title: '播放列表为空，请先选择歌曲',
      icon: 'none'
    })
  }
}

const handlePrev = () => {
  innerAudioContext.stop()
  sliderIndex.value = 0
  currentTimeText.value = '00:00'
  currentTime2.value = 0
  if (index == 0) {
    index = audioList.value.length
  }
  

  innerAudioContext.src = audioList.value[index - 1].audioUrlUrl
  // song.value.title = audioList.value[index - 1].title
  // song.value.imageUrlUrl = audioList.value[index - 1].imageUrlUrl
  // song.value.duration = audioList.value[index - 1].duration
  // song.value.lyric = audioList.value[index - 1].lyric
  song.value = audioList.value[index - 1]
  innerAudioContext.play()
  isPlay.value = true
  index -= 1
  console.log(index, 'index')
  getCommentByMusic(song.value.musicId)
}
const handleNext = () => {
  innerAudioContext.stop()
  sliderIndex.value = 0
  currentTimeText.value = '00:00'
  currentTime2.value = 0
  console.log(sliderIndex.value, currentTimeText.value, '下一首')
  if (index == audioList.value.length - 1) {
    index = -1
  }

  innerAudioContext.src = audioList.value[index + 1].audioUrlUrl
  // song.value.title = audioList.value[index + 1].title
  // song.value.imageUrlUrl = audioList.value[index + 1].imageUrlUrl
  // song.value.duration = audioList.value[index + 1].duration
  // song.value.lyric = audioList.value[index + 1].lyric
  song.value = audioList.value[index + 1]
  innerAudioContext.play()
  isPlay.value = true
  index += 1
  console.log(index, 'index')
  console.log(song.value, 'song.value');
  getCommentByMusic(song.value.musicId)
  
  
}

// 文件下载
// const onFileDownload = async (drawing: any) => {
//   uni.setClipboardData({
//       data: drawing,
//       success: function () {
//           uni.showToast({ title: '复制成功，请打开浏览器下载', duration: 2000 })
//       }
//   })
// }

// const data = reactive({
//   list: [
//     {
//       text: '下载音频',
//       fontSize: 28
//     },
//     {
//       text: '下载视频',
//       fontSize: 28
//     }
//   ]
// })
// const sheetClick = (index: number) => {
//   if (index == 0) {
//     onFileDownload(song.value.audioUrl)
//   } else if (index == 1) {
//     onFileDownload(song.value.videoUrl)
//   }
// }
//变更滑块位置
const handleSliderChange = (e) => {
  changePlayProgress(e.detail ? e.detail.value : e)
}
//更改播放进度
const changePlayProgress = (value: any) => {
  sliderIndex.value = value
  innerAudioContext.seek(value)
  currentTimeText.value = moment(value * 1000).format('mm:ss')
}
// tabs部分
const current = ref(0)
const list1 = ref([
  { title: '歌曲', key: 0 },
  { title: '评论', key: 1 }
])

const handleChange = (index: number) => {
  current.value = index
  console.log(current.value, 'current.value');

}
const starClick = () => {
  uni.showToast({ title: '敬请期待' })
}
// const shareClick = () => {
//   uni.showToast({ title: '敬请期待' })
// }
onUnmounted(() => {
  innerAudioContext.destroy()
})
</script>

<style lang="scss" scoped>
.songDetailContainer {
  height: 100vh;
  width: 100%;

  position: relative;

  .bg {
    width: 100%;
    height: 100vh;
    position: absolute;
    z-index: 0;
    background-size: cover;
    background-repeat: no-repeat;
    filter: blur(60px);
  }

  .content {
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    align-items: center;

    .title {
      color: #fff;
      position: absolute;
      top: 30rpx;
    }

    .prompt {
      color: #fff;
      position: absolute;
      top: 80rpx;
      left: 40rpx;
      right: 40rpx;
      font-size: 38rpx;
      line-height: 68rpx;
    }

    .h-full {
      position: absolute;
      top: 120rpx;
      left: 40rpx;
      right: 40rpx;
      height: 800rpx;
      width: calc(100% - 80rpx);
    }

    .u-tabs-con {
      position: absolute;
      bottom: 300rpx;
      left: 250rpx;
    }
  }
}

.content ::v-deep .u-tabs {
  background: none !important;
}

.share {
  position: absolute;
  bottom: 320rpx;
  right: 50rpx;
  color: #fff;
  display: flex;
  align-items: center;

  text {
    margin-left: 10rpx;
    font-size: 24rpx;
  }
}

/* 磁盘 */
.discContainer {
  position: relative;
  top: 200rpx;
  // width: 598rpx;
  // height: 598rpx;
  width: 490rpx;
  height: 490rpx;
  border: 1rpx solid #e6e6e6;
  border-radius: 50%;
}

.discAnimation {
  animation: disc 8s linear infinite;
  animation-delay: 1s;
}

/*
@keyframes: 设置动画帧
  1) from to
    - 使用于简单的动画，只有起始帧和结束帧
    - 北京 - 上海  直达
  2) 百分比
    - 多用于复杂的动画，动画不止两帧
    - 北京 - 上海 ---> 北京 -- 天津 --- 深圳 --- 上海
    - 0% - 100%, 可以任意拆分
*/
@keyframes disc {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.disc {
  width: 100%;
  height: 100%;
}

.paused {
  animation-name: disc;
  animation-play-state: paused;
  animation-duration: 1s;
  animation-fill-mode: both;
}

.running {
  animation: disc 8s linear infinite;
}

.songDetailContainer .discContainer .musicImg {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  width: 370rpx;
  height: 370rpx;
  border: 1rpx solid transparent;
  border-radius: 50%;
}

.circle {
  position: absolute;
  left: 30rpx;
  top: 30rpx;
  width: 430rpx;
  height: 430rpx;
  border: 1rpx solid #e6e6e6;
  border-radius: 50%;
}

/* 底部控制播放区域 */
.musicControl {
  position: absolute;
  bottom: 80rpx;
  left: 60rpx;
  width: calc(100% - 120rpx);
  display: flex;
  justify-content: space-between;
}

.musicControl text {
  width: 20%;
  height: 120rpx;
  line-height: 120rpx;
  text-align: center;
  color: #fff;
  font-size: 50rpx;
}

.musicControl text.big {
  font-size: 80rpx;
}

/* 进度条控制区域 */
.progressControl {
  position: absolute;
  bottom: 200rpx;
  width: 640rpx;
  height: 80rpx;
  line-height: 80rpx;
  display: flex;
  color: #fff;
}

.action-sheet ::v-deep .u-action-sheet-item {
  align-items: baseline;
  padding-left: 30rpx;
}

::v-deep .py-12 {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
